<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>供应商管理系统</title>
    <meta name="description" content="这是一个 index 页面">
    <meta name="keywords" content="index">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <link rel="icon" type="image/png" href="assets/i/favicon.png">
    <link rel="apple-touch-icon-precomposed" href="assets/i/app-icon72x72@2x.png">
    <meta name="apple-mobile-web-app-title" content="Amaze UI"/>
    <link rel="stylesheet" href="assets/css/amazeui.min.css"/>
    <link rel="stylesheet" href="assets/css/admin.css">
    <link rel="stylesheet" href="assets/css/app.css">
</head>

<body data-type="generalComponents">
<header class="am-topbar am-topbar-inverse admin-header">
    <div class="am-collapse am-topbar-collapse" id="topbar-collapse">
        <ul class="am-nav am-nav-pills am-topbar-nav am-topbar-right admin-header-list tpl-header-list">
            <li class="am-dropdown" data-am-dropdown data-am-dropdown-toggle>
                <a class="am-dropdown-toggle tpl-header-list-link" href="javascript:;">
                    <span class="tpl-header-list-user-nick" id="currentUserName">暂无昵称</span><span class="tpl-header-list-user-ico"> <img
                        src="assets/img/user01.png"></span>
                </a>
                <ul class="am-dropdown-content">
                    <li><a href="login.html"><span class="am-icon-power-off"></span> 退出</a></li>
                </ul>
            </li>
        </ul>
    </div>
</header>
<div class="tpl-page-container tpl-page-header-fixed">
    <div class="tpl-left-nav tpl-left-nav-hover">
        <div class="tpl-left-nav-list">
            <ul class="tpl-left-nav-menu">
                <li class="tpl-left-nav-item">
                    <a href="javascript:;" class="nav-link tpl-left-nav-link-list">
                        <i class="am-icon-wpforms"></i>
                        <span>企业管理</span>
                        <i class="am-icon-angle-right tpl-left-nav-more-ico am-fr am-margin-right"></i>
                    </a>
                    <ul class="tpl-left-nav-sub-menu">
                        <li>
                            <a href="info-certification.html">
                                <i class="am-icon-angle-right"></i>
                                <span>企业信息认证</span>
                            </a>
                        </li>
                    </ul>
                </li>
                <li class="tpl-left-nav-item">
                    <a href="javascript:;" class="nav-link tpl-left-nav-link-list active">
                        <i class="am-icon-table"></i>
                        <span>供应商管理</span>
                        <i class="am-icon-angle-right tpl-left-nav-more-ico am-fr am-margin-right tpl-left-nav-more-ico-rotate"></i>
                    </a>
                    <ul class="tpl-left-nav-sub-menu" style="display:block">
                        <li>
                            <a href="white-list.html" class="active">
                                <i class="am-icon-angle-right"></i>
                                <span>供应商白名单</span>
                            </a>
                            <a href="black-list.html">
                                <i class="am-icon-angle-right"></i>
                                <span>供应商黑名单</span>
                            </a>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
    <div class="tpl-content-wrapper">
        <div class="tpl-content-page-title">
            供应商白名单列表
        </div>
        <ol class="am-breadcrumb">
            <li class="am-active"><a style="color: #999999;">供应商管理</a></li>
            <li class="am-active">供应商白名单</li>
        </ol>
        <div class="tpl-portlet-components">
            <div class="tpl-block">
                <div class="am-g">
                    <div class="am-u-sm-6 am-u-md-2">
                        <div class="am-input-group am-input-group-sm">
                                <span class="am-input-group-btn">
                                    <span style="font-size: 14px;margin-right: 8px;margin-left: 8px">企业名称</span>
                                </span>
                            <input type="text" id="searchSupplierName" class="am-form-field" placeholder="&nbsp;&nbsp;请输入企业名称"
                                   style="border: 1px solid #c2cad8;border-radius: 3px;">
                        </div>
                    </div>
                    <div class="am-u-sm-6 am-u-md-3">
                        <div class="am-form-group">
                            <span style="font-size: 14px;">企业评级</span>
                            <select id="searchSupplierLevel" data-am-selected="{btnSize: 'sm'}">
                                <option value="">请选择企业评级</option>
                                <option value="A">1级</option>
                                <option value="B">2级</option>
                                <option value="C">3级</option>
                            </select>
                        </div>
                    </div>
                    <div style="float:right">
                        <div class="am-form-group" style="margin-right: 10px;">
                            <button type="button" class="am-btn am-btn-default am-btn-sm" id="searchBtn">搜索</button>
                            <button type="button" class="am-btn am-btn-secondary am-btn-sm" id="resetBtn">重置</button>
                            <button type="button" class="am-btn am-btn-primary am-btn-sm"
                                    id="doc-prompt-toggle">添加供应商
                            </button>
                        </div>
                    </div>
                </div>
                <div class="am-g">
                    <div class="am-u-sm-12">
                        <form class="am-form">
                            <table class="am-table am-table-striped am-table-hover table-main">
                                <thead>
                                <tr>
                                    <th class="table-id">序号</th>
                                    <th class="table-title">企业名称</th>
                                    <th class="table-type">企业联系人</th>
                                    <th class="table-author am-hide-sm-only">联系方式</th>
                                    <th class="table-date am-hide-sm-only">联系邮箱</th>
                                    <th class="table-date am-hide-sm-only">企业评级</th>
                                    <th class="table-date am-hide-sm-only">更新日期</th>
                                    <th class="table-set">操作</th>
                                </tr>
                                </thead>
                                <tbody id="whiteListTableBody">
                                <!-- 数据将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                            <div class="am-cf">
                                <div class="am-fr">
                                    <ul class="am-pagination tpl-pagination" id="pagination">
                                        <!-- 分页将通过JavaScript动态生成 -->
                                    </ul>
                                </div>
                            </div>
                            <hr>
                        </form>
                        <!-- 添加供应商弹出框 -->
                        <div class="am-modal am-modal-prompt" tabindex="-1" id="my-prompt">
                            <div class="am-modal-dialog">
                                <form action="" class="am-form am-form-horizontal">
                                    <legend style="font-size: 18px;padding: 12px 0;">添加供应商</legend>
                                    <div class="am-form-group">
                                        <label for="addSupplierSelect" class="am-u-sm-4 am-form-label"
                                               style="font-size: 15px;">企业名称</label>
                                        <div class="am-u-sm-6">
                                            <select id="addSupplierSelect" required>
                                                <option value="">请选择企业</option>
                                                <!-- 企业选项将通过JavaScript动态加载 -->
                                            </select>
                                        </div>
                                        <span class="am-form-caret"></span>
                                    </div>
                                    <div class="am-form-group">
                                        <label for="addSupplierCreditCode" class="am-u-sm-4 am-form-label"
                                               style="font-size: 15px;">统一社会信用代码</label>
                                        <div class="am-u-sm-6" style=" text-align: left;margin-top: 6px;">
                                            <span id="addSupplierCreditCode">请先选择企业</span>
                                        </div>
                                        <span class="am-form-caret"></span>
                                    </div>
                                    <div class="am-form-group" style="margin-bottom: 20px;">
                                        <label for="addSupplierLevel" class="am-u-sm-4 am-form-label"
                                               style="font-size: 15px;">企业评级</label>
                                        <div class="am-u-sm-6">
                                            <select id="addSupplierLevel" required>
                                                <option value="">请选择企业评级</option>
                                                <option value="A">1级</option>
                                                <option value="B">2级</option>
                                                <option value="C">3级</option>
                                            </select>
                                        </div>
                                        <span class="am-form-caret"></span>
                                    </div>
                                </form>
                                <div class="am-modal-footer" style="border-top: 1px solid #dedede;">
                                    <span class="am-modal-btn" data-am-modal-cancel>取消</span>
                                    <span class="am-modal-btn" data-am-modal-confirm>提交</span>
                                </div>
                            </div>
                        </div>
                        <!-- 确认添加至黑名单弹出框 -->
                        <div class="am-modal am-modal-confirm" tabindex="-1" id="confirm-blacklist-modal">
                            <div class="am-modal-dialog">
                                <div class="am-modal-hd">提示</div>
                                <div class="am-modal-bd">
                                    将供应商添加至黑名单后该企业将无法在平台进行融资，是否继续？
                                </div>
                                <div class="am-modal-footer">
                                    <span class="am-modal-btn" data-am-modal-cancel>取消</span>
                                    <span class="am-modal-btn" data-am-modal-confirm>确定</span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 添加至黑名单弹出框 -->
                        <div class="am-modal am-modal-prompt" tabindex="-1" id="blacklist-modal">
                            <div class="am-modal-dialog">
                                <form action="" class="am-form am-form-horizontal">
                                    <legend style="font-size: 18px;padding: 12px 0;">添加至黑名单</legend>
                                    <div class="am-form-group">
                                        <label class="am-u-sm-4 am-form-label"
                                               style="font-size: 15px;">企业名称</label>
                                        <div class="am-u-sm-6" style=" text-align: left;margin-top: 6px;">
                                            <span id="blacklist-supplier-name">-</span>
                                        </div>
                                        <span class="am-form-caret"></span>
                                    </div>
                                    <div class="am-form-group">
                                        <label class="am-u-sm-4 am-form-label"
                                               style="font-size: 15px;">统一社会信用代码</label>
                                        <div class="am-u-sm-6" style=" text-align: left;margin-top: 6px;">
                                            <span id="blacklist-supplier-code">-</span>
                                        </div>
                                        <span class="am-form-caret"></span>
                                    </div>
                                    <div class="am-form-group" style="margin-bottom: 20px;">
                                        <label class="am-u-sm-4 am-form-label"
                                               style="font-size: 15px;">添加理由</label>
                                        <div class="am-u-sm-6">
                                            <textarea class="" rows="4" id="blacklist-reason"
                                                      placeholder="请输入添加理由">从白名单移至黑名单</textarea>
                                        </div>
                                        <span class="am-form-caret"></span>
                                    </div>
                                </form>
                                <div class="am-modal-footer" style="border-top: 1px solid #dedede;">
                                    <span class="am-modal-btn" data-am-modal-cancel>取消</span>
                                    <span id="blacklist-submit-btn" class="am-modal-btn" data-am-modal-confirm>提交</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="tpl-alert"></div>
        </div>
    </div>
</div>

<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/amazeui.min.js"></script>
<script src="assets/js/app.js"></script>
<script>
    // 全局变量：当前页码（默认第一页）、可用企业列表（未加入白名单的企业）
    let currentPage = 1;
    let availableEnterprises = [];

    // 页面加载完成后初始化
    $(document).ready(function() {
        loadCurrentUserInfo(); // 加载当前登录用户信息（用于显示用户名）
        loadWhiteList(1); // 加载第一页白名单数据
        loadAvailableEnterprises();// 加载可添加到白名单的企业列表
    });

    /**
     * 加载当前登录用户信息
     * 功能：从后端接口获取用户信息，更新导航栏用户名显示；未登录则跳转至登录页
     */
    function loadCurrentUserInfo() {
        $.get('/asd/login/getCurrentUser', function(response) {
            // 处理未登录情况（后端返回字符串提示）
            if (typeof response === 'string' && response.indexOf('未登录') > -1) {
                alert('用户未登录，请先登录');
                window.location.href = 'login.html';
                return;
            }

            // 处理对象类型的响应（已登录情况）
            if (typeof response === 'object' && response.account) {
                // 更新导航栏用户名显示
                if (response.name && response.name.trim() !== '') {
                    $('#currentUserName').text(response.name);
                } else {
                    $('#currentUserName').text('暂无昵称');
                }
            } else {
                $('#currentUserName').text('暂无昵称');
            }
        }, 'json') // 指定响应数据类型为 JSON，便于自动解析
            .fail(function() {

                // 请求失败处理（如网络错误、后端异常）
                $('#currentUserName').text('暂无昵称');
                console.error('获取用户信息失败');
            });
    }

    /**
     * 加载白名单数据（分页查询）
     * page - 要加载的页码（从1开始）
     * 功能：向后端发起GET请求获取指定页的白名单数据，成功后渲染表格和分页控件
     */
    function loadWhiteList(page) {
        // 更新当前页码为传入的目标页码
        currentPage = page;
        // 发起AJAX GET请求，请求后端分页接口，携带页码参数
        $.get('/asd/whitelist/getWhiteListByPage', { pageIndex: page }, function(response) {
            try {
                // 处理响应数据：若后端返回字符串则手动解析为JSON，否则直接使用（jQuery可能已自动解析）
                const data = typeof response === 'string' ? JSON.parse(response) : response;
                // 判断响应是否包含有效数据（后端约定data字段存储白名单列表）
                if (data.data) {
                    renderWhiteListTable(data.data);
                    renderPagination(data.currentPage, data.totalPages, data.totalCount);
                } else {
                    alert(data || '加载失败');
                }
            } catch (e) {
                console.error('解析数据失败:', e);
                alert('数据格式错误');
            }
        })
            .fail(function() {
                alert('网络请求失败');
            });
    }

    // 搜索白名单
    function searchWhiteList(page = 1) {
        const supplierName = $('#searchSupplierName').val().trim();
        const supplierLevel = $('#searchSupplierLevel').val();

        $.get('/asd/whitelist/searchWhiteList', {
            supplierName: supplierName,
            supplierLevel: supplierLevel,
            pageIndex: page
        }, function(response) {
            try {
                // 检查响应是否已经是对象（jQuery自动解析）还是字符串
                const data = typeof response === 'string' ? JSON.parse(response) : response;
                if (data.data) {
                    renderWhiteListTable(data.data);
                    renderPagination(data.currentPage, data.totalPages, data.totalCount);
                    currentPage = page;
                } else {
                    alert(data || '搜索失败');
                }
            } catch (e) {
                console.error('解析数据失败:', e);
                alert('数据格式错误');
            }
        })
            .fail(function() {
                alert('网络请求失败');
            });
    }

    // 渲染白名单表格
    function renderWhiteListTable(data) {
        const tbody = $('#whiteListTableBody');
        tbody.empty();
        
        if (data.length === 0) {
            tbody.append(`
                <tr>
                    <td colspan="8" style="text-align: center;">暂无数据</td>
                </tr>
            `);
            return;
        }

        data.forEach(function(item, index) {
            const levelText = item.supplierLevel === 'A' ? '1级' : 
                             item.supplierLevel === 'B' ? '2级' : '3级';
            const updateDate = item.updateDate || '-';
            
            const row = `
                <tr data-supplier-id="${item.supplierId}">
                    <td>${(currentPage - 1) * 5 + index + 1}</td>
                    <td class="am-hide-sm-only"><a href="#">${item.supplierName || '-'}</a></td>
                    <td class="am-hide-sm-only">${item.supplierContact || '-'}</td>
                    <td class="am-hide-sm-only">${item.supplierPhone || '-'}</td>
                    <td class="am-hide-sm-only">${item.supplierEmail || '-'}</td>
                    <td class="am-hide-sm-only">
                        <div class="">
                            <select data-am-selected="{btnSize: 'xs'}" onchange="updateSupplierLevel(${item.supplierId}, this.value)">
                                <option value="A" ${item.supplierLevel === 'A' ? 'selected' : ''}>1级</option>
                                <option value="B" ${item.supplierLevel === 'B' ? 'selected' : ''}>2级</option>
                                <option value="C" ${item.supplierLevel === 'C' ? 'selected' : ''}>3级</option>
                            </select>
                        </div>
                    </td>
                    <td class="am-hide-sm-only">${updateDate}</td>
                    <td>
                        <div class="am-btn-toolbar">
                            <div class="am-btn-group am-btn-group-xs">
                                <span class="am-text-secondary am-icon remove-from-whitelist"
                                      style="margin-left: 20px;cursor:pointer" 
                                      data-supplier-id="${item.supplierId}"
                                      data-supplier-name="${item.supplierName}"
                                      data-supplier-code="${item.supplierSocialUniformCode || '-'}">
                                    <span></span>添加至黑名单
                                </span>
                            </div>
                        </div>
                    </td>
                </tr>
            `;
            tbody.append(row);
        });
    }

    // 渲染分页
    function renderPagination(currentPage, totalPages, totalCount) {
        const pagination = $('#pagination');
        pagination.empty();
        
        if (totalPages <= 1) return;

        // 上一页
        const prevClass = currentPage === 1 ? 'am-disabled' : '';
        pagination.append(`
            <li class="${prevClass}">
                <a href="javascript:void(0)" onclick="changePage(${currentPage - 1})">&laquo;</a>
            </li>
        `);

        // 页码
        for (let i = 1; i <= totalPages; i++) {
            const activeClass = i === currentPage ? 'am-active' : '';
            pagination.append(`
                <li class="${activeClass}">
                    <a href="javascript:void(0)" onclick="changePage(${i})">${i}</a>
                </li>
            `);
        }

        // 下一页
        const nextClass = currentPage === totalPages ? 'am-disabled' : '';
        pagination.append(`
            <li class="${nextClass}">
                <a href="javascript:void(0)" onclick="changePage(${currentPage + 1})">&raquo;</a>
            </li>
        `);
    }

    // 切换页面
    function changePage(page) {
        if (page < 1) return;
        
        const supplierName = $('#searchSupplierName').val().trim();
        const supplierLevel = $('#searchSupplierLevel').val();
        
        if (supplierName || supplierLevel) {
            searchWhiteList(page);
        } else {
            loadWhiteList(page);
        }
    }

    // 更新供应商评级
    function updateSupplierLevel(supplierId, newLevel) {
        // 这里可以添加更新评级的AJAX请求
        console.log('更新供应商评级:', supplierId, newLevel);
    }

    // 加载可用企业列表
    function loadAvailableEnterprises() {
        $.get('/asd/whitelist/getAvailableEnterprises', function(response) {
            try {
                // 检查响应是否已经是对象（jQuery自动解析）还是字符串
                availableEnterprises = typeof response === 'string' ? JSON.parse(response) : response;
                renderEnterpriseOptions();
            } catch (e) {
                console.error('解析企业数据失败:', e);
                console.log('原始响应:', response);
            }
        })
            .fail(function() {
                console.error('获取可用企业列表失败');
            });
    }


    // 渲染企业选项
    function renderEnterpriseOptions() {
        const $select = $('#addSupplierSelect');
        // 保留第一个选项，清空其他选项
        $select.children().not(':first').remove();

        // 使用箭头函数和模板字符串简化循环
        availableEnterprises.forEach(enterprise => {
            $select.append(`<option value="${enterprise.id}">${enterprise.name}</option>`);
        });
    }

    // 搜索按钮点击事件
    $('#searchBtn').on('click', function() {
        searchWhiteList(1);
    });

    // 重置按钮点击事件
    $('#resetBtn').on('click', function() {
        $('#searchSupplierName').val('');
        $('#searchSupplierLevel').val('');
        loadWhiteList(1);
    });

    // 企业选择变化时更新信用代码
    $('#addSupplierSelect').on('change', function() {
        const selectedId = $(this).val();
        const enterprise = availableEnterprises.find(e => e.id == selectedId);
        
        if (enterprise) {
            $('#addSupplierCreditCode').text(enterprise.creditCode || '暂无');
        } else {
            $('#addSupplierCreditCode').text('请先选择企业');
        }
    });


    // 添加供应商弹窗
    $('#doc-prompt-toggle').on('click', function() {
        loadAvailableEnterprises(); // 重新加载可用企业
        $('#my-prompt').modal({
            relatedTarget: this,
            onConfirm: function() {
                const supplierId = $('#addSupplierSelect').val();
                const supplierLevel = $('#addSupplierLevel').val();

                if (!supplierId || !supplierLevel) {
                    alert('请完整填写信息');
                    return false;
                }

                // 添加到白名单（与登录请求风格一致）
                $.post("/asd/whitelist/addToWhiteList", {
                    "supplierId": supplierId,
                    "supplierLevel": supplierLevel
                }, function(result) {
                    let message = '';

                    // 处理不同类型的响应
                    if (typeof result === 'string') {
                        message = result;
                    } else if (result && result.message) {
                        message = result.message;
                    } else {
                        message = '添加成功';
                    }

                    alert(message);

                    // 刷新列表
                    loadWhiteList(currentPage);
                    // 重置表单
                    $('#addSupplierSelect').val('');
                    $('#addSupplierLevel').val('');
                    $('#addSupplierCreditCode').text('请先选择企业');
                })
                    .fail(function() {
                        alert('网络请求失败');
                    });
            },
            onCancel: function() {
                // 重置表单
                $('#addSupplierSelect').val('');
                $('#addSupplierLevel').val('');
                $('#addSupplierCreditCode').text('请先选择企业');
            }
        });
    });

    // 移除白名单（添加至黑名单）- 第一步：显示详细信息弹窗
    $(document).on('click', '.remove-from-whitelist', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        const supplierId = $(this).data('supplier-id');
        const supplierName = $(this).data('supplier-name');
        const supplierCode = $(this).data('supplier-code');
        
        console.log('点击添加至黑名单，直接显示详细信息弹窗');
        
        // 直接显示详细信息弹窗
        showBlacklistDetailModal(supplierId, supplierName, supplierCode);
    });
    
    // 显示添加至黑名单详细弹窗
    function showBlacklistDetailModal(supplierId, supplierName, supplierCode) {
        console.log('显示详细弹窗，供应商:', supplierName);
        
        // 填充模态框信息
        $('#blacklist-supplier-name').text(supplierName || '-');
        $('#blacklist-supplier-code').text(supplierCode || '-');
        $('#blacklist-reason').val('从白名单移至黑名单');
        
        // 存储供应商ID供提交时使用
        $('#blacklist-modal').data('supplier-id', supplierId);
        
        // 显示模态框
        $('#blacklist-modal').modal('open');
    }

    // 处理黑名单模态框的提交按钮
    // 详细弹窗的提交按钮 - 显示确认弹窗
    $(document).on('click', '#blacklist-submit-btn', function() {
        const supplierId = $('#blacklist-modal').data('supplier-id');
        const reason = $('#blacklist-reason').val().trim();
        
        if (!reason) {
            alert('请输入添加到黑名单的理由');
            return;
        }
        
        console.log('详细弹窗提交，显示确认弹窗，理由:', reason);
        
        // 保存数据供确认弹窗使用
        window.tempBlacklistData = {
            supplierId: supplierId,
            reason: reason
        };
        
        // 关闭详细弹窗
        $('#blacklist-modal').modal('close');
        
        // 延迟一下再显示确认弹窗
        setTimeout(function() {
            $('#confirm-blacklist-modal').modal('open');
        }, 300);
    });
    
    // 处理确认弹窗的确定按钮 - 真正执行添加至黑名单操作
    $(document).on('click', '#confirm-blacklist-modal [data-am-modal-confirm]', function() {
        console.log('确认弹窗点击确定，执行添加至黑名单操作');

        if (window.tempBlacklistData) {
            // 关闭确认弹窗
            $('#confirm-blacklist-modal').modal('close');

            // 执行真正的移除白名单操作（使用$.post简化）
            $.post('/asd/whitelist/removeFromWhiteList', {
                "supplierId": window.tempBlacklistData.supplierId,
                "reason": window.tempBlacklistData.reason
            }, function(result) {
                console.log('移除供应商响应:', result);
                console.log('响应类型:', typeof result);

                let message = '';

                // 处理不同类型的响应
                if (typeof result === 'string') {
                    message = result;
                } else if (result && result.message) {
                    message = result.message;
                } else {
                    message = '移除成功';
                }

                alert(message);

                // 刷新列表
                loadWhiteList(currentPage);
            })
                .fail(function() {
                    alert('网络请求失败');
                });
        }
    });
</script>
</body>

</html>